package club.kingyin.kyblog.controller;

import club.kingyin.kyblog.core.IP;
import club.kingyin.kyblog.core.PassToken;
import club.kingyin.kyblog.core.business.dao.admin.Info;
import club.kingyin.kyblog.core.business.dao.admin.Token;
import club.kingyin.kyblog.core.business.dao.admin.User;
import club.kingyin.kyblog.core.business.dto.ResultUtil;
import club.kingyin.kyblog.core.business.service.admin.AdminService;
import club.kingyin.kyblog.core.extend.IPSetPostProcessor;
import club.kingyin.kyblog.core.utils.cache.Cache;
import club.kingyin.kyblog.core.utils.log.LogConsole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * @author ：kingyin
 * @date ：创建于 2021/8/13 12:17 上午
 * @description ：
 * @modified By：
 * @version: 1.0.0
 */
@IP
@RestController
@RequestMapping("/vue-element-admin/user")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @PassToken
    @LogConsole(module = "后台登录", operator = "九命可", sources = IPSetPostProcessor.class)
    @PostMapping("/login")
    public ResultUtil login(@RequestBody User user) {
        Token login = adminService.login(user);
        if (login == null) {
            return ResultUtil.fail("用户名或密码错误");
        }
        return ResultUtil.success(login);
    }

    @PassToken
    @Cache(module = "后台信息", operator = "九命可", expire = 1000 * 60 * 60, sources = IPSetPostProcessor.class)
    @RequestMapping("/info")
    public ResultUtil info(@RequestHeader("X-Token") String token) {
        Info info = adminService.getInfo(token);
        if (info == null) {
            return ResultUtil.fail("权限验证失败");
        }
        return ResultUtil.success(info);
    }

    @PassToken
    @LogConsole(module = "用户修改", operator = "九命可", sources = IPSetPostProcessor.class)
    @GetMapping("/update")
    public ResultUtil update(@RequestHeader("X-Token") String token, @RequestParam("name")String name) {
        // 更新需要把所属文章的作者也更新
        if (adminService.update(token, name)) {
            return ResultUtil.success("更新成功");
        }
        return ResultUtil.fail("更新失败");
    }
    @LogConsole(module = "后台登出", operator = "九命可", sources = IPSetPostProcessor.class)
    @PostMapping("/logout")
    public ResultUtil logout(@RequestHeader("X-Token") String token) {
        return adminService.logout(token) ? ResultUtil.success("已退出") : ResultUtil.fail("退出失败");
    }
}
